import re
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from meiduo_mall.utils.DBHelper import create_redis_conn
from users.models import User, Address
from goods.models import SKU


class RegisterSerializers(serializers.ModelSerializer):
    """用户注册序列化器"""
    password2 = serializers.CharField(label="确定密码", write_only=True)
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    allow = serializers.CharField(label="是否同意协议", write_only=True)
    token = serializers.CharField(label="登录状态token", read_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号码格式不正确')
        count = User.objects.filter(mobile=value).count()
        if count > 0:
            raise serializers.ValidationError('该手机号已经被注册')
        return value

    def validate_allow(self, value):
        if not value == 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, value):
        password = value['password']
        password2 = value['password2']
        if password != password2:
            raise serializers.ValidationError('两次输入的密码不一致')

        conn = create_redis_conn("sms_code")
        real_sms_code = (conn.get("sms_code_%s" % value["mobile"])).decode('utf-8')
        if real_sms_code is None:
            raise serializers.ValidationError("验证码已过期")
        if real_sms_code != value["sms_code"]:
            raise serializers.ValidationError("错误的验证码")
        return value

    def create(self, validated_data):
        print(validated_data)
        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]
        user = super().create(validated_data)
        # user = User.objects.create_user(validated_data['username'], validated_data['password'])
        # user = super().create_user(validated_data)
        user.set_password(validated_data['password'])
        user.save()

        # 生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = email
        instance.save()

        # 生成验证连接
        verify_url = instance.generate_verify_email_url()
        # 发送验证邮件
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)
        return instance


class AddressSerializers(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super(AddressSerializers, self).create(validated_data)
        # return Address.objects.create_user(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('title',)


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label="商品SKU编号")
    # class Meta:
    #     model = SKU
    #     fields = ('id',)

    def validate_sku_id(self, data):
        try:
            SKU.objects.get(id=data)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return data

    def create(self, validated_data):
        user = self.context['request'].user
        print(user)
        # 建立该用户的访问历史记录的red qis数据库连接
        redis_conn = create_redis_conn('history')
        # 创建redis的管道进行数据的修改
        pl = redis_conn.pipeline()
        # 删除所有值为当前sku_id的值
        pl.lrem("history_%s" % user.id, 0, validated_data['sku_id'])
        pl.lpush("history_%s" % user.id, validated_data['sku_id'])
        pl.ltrim("history_%s" % user.id, 0, -1)
        pl.execute()
        return validated_data


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url')
